<template>
  <div class="tab">
    <cube-tab-bar
      ref="tabBar"
      class="border-bottom-1px"
      v-model="selectedLabel"
      :useTransition="false"
      :showSlider="true"
      :data="tabs"
      @click="clickHandler"
    >
    </cube-tab-bar>
    <div class="slide-wrapper">
      <cube-slide 
        ref="slide"
        :initial-index="index"
        :data="tabs" 
        :loop="false"
        :show-dots="false"
        :autoPlay="false"
        :options="slideOptions"
        @change="onChange"
        @scroll="onScroll"
      >
        <cube-slide-item v-for="(tab, index) in tabs" :key="index">
          <component
            ref="component"
            :is="tab.component"
            :data="tab.data"
          >
          </component>
        </cube-slide-item>
      </cube-slide>
    </div>
  </div>
</template>

<script>
  export default {
    name: "tab",
    props: {
      tabs: {
        type: Array,
        default() {
          return []
        } 
      },
      initialIndex: {
        type: Number,
        default: 0
      }
    },
    data () {
      return {
        // selectedLabelDefault: '商品',
        index: this.initialIndex,
        slideOptions: {
          listenScroll: true,
          probeType: 3,
          directionLockThreshold: 0
        }
      }
    },
    computed: {
      selectedLabel: {
        get() {
          return this.tabs[this.index].label
        },
        set(newValue) {
          // console.log(newValue)
          this.index = this.tabs.findIndex((value) => {
            return value.label === newValue
          })
        }        
      }
    },
    mounted() {
      this.onChange(this.index)
      // console.log(this.$refs.tabBar);
      // console.log(this.$refs.slide);
    },
    methods: {
      clickHandler (label) {
        // if you clicked home tab, then print 'Home'
        console.log(label)
      },
      // 组件切换时，暴露出的@change事件
      onChange(current) {
        this.index = current
        const component = this.$refs.component[current]
        component.fetch && component.fetch()
      },
      // 页面切换时，标签底部的跟随滚动效果
      onScroll(pos) {
        // console.log(pos)
        // console.log(this.$refs.slide)
        const tabBarWidth = this.$refs.tabBar.$el.clientWidth
        const slideWidth = this.$refs.slide.slide.scrollerWidth
        const transform = -pos.x / slideWidth * tabBarWidth
        this.$refs.tabBar.setSliderTransform(transform)
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "~common/stylus/variable.styl"

  .tab
    display: flex
    flex-direction: column
    // width: 100%
    height: 100%
    >>> .cube-tab
      // display: inline-block
      padding: 10px 0
    .slide-wrapper
      flex: 1
      overflow: hidden
</style>
